package com.wonder.constant;

public class BillNoGenerator {

    private static long lastTimestamp = 0L;
    private static int sequence = 0;
    private static final int MAX_SEQUENCE = 999;

    private BillNoGenerator() {}

    public static synchronized String createBillNo(BillType billType) {
        long timestamp = System.currentTimeMillis();

        if (timestamp == lastTimestamp) {
            sequence++;
            if (sequence > MAX_SEQUENCE) {
                timestamp = waitNextMillis(lastTimestamp);
                sequence = 0;
            }
        } else {
            sequence = 0;
        }
        lastTimestamp = timestamp;

        String time = new java.text.SimpleDateFormat("yyMMddHHmmssSSS")
                .format(new java.util.Date(timestamp));

        String billNo = billType.toString() + time;
        if (sequence > 0) {
            billNo += String.format("%03d", sequence);
        }
        return billNo;
    }

    private static long waitNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}
